<template>
	<view class="ana-ad">
		<view class="header">
			<wuc-tab :tab-list="navItems" :tabCur.sync="activeIndex" textFlex tab-class="text-center bg-white wuc-tab"  @change="tabChange"></wuc-tab>
		</view>
		<!-- 销售分析 -->
		<view class="c-bd" v-show="activeIndex == 0">
			<view class="selects flex">
				<view class="tit">时间</view>
				<view class="content flex">
					<view class="st-time" :class="[beginDate ?'':'placeholder']" @tap="toggleTab('range')">{{beginDate?beginDate:'开始时间'}}</view>
					<view>至</view>
					<view class="ed-time" :class="[endDate ?'':'placeholder']" @tap="toggleTab('range')">{{endDate?endDate:'结束时间'}}</view>
				</view>
			</view>
			<view>
				<canvas v-show="!radarImg" canvas-id="canvasColumn" id="canvasColumn" class="charts" disable-scroll=true @touchstart="touchColumn" @touchmove="moveColumn" @touchend="touchEndColumn"></canvas>
				<image v-if="radarImg" :src="radarImg" class="radarImg"></image>
			</view>
			<view class="total">销售总额：{{salesTotal}}</view>
		</view>
		<!-- 数据看板 -->
		<view class="c-bd" v-show="activeIndex == 1">
			<view class="kanban flex">
				<view class="item">
					<view class="tit">客户量</view>
					<view class="num">{{kanbanDatas.allCustomerCount}}</view>
					<view class="tag">总</view>
				</view>
				<view class="item">
					<view class="tit">新增客户</view>
					<view class="num">{{kanbanDatas.customerCountThisWeek}}</view>
					<view class="tag">本周</view>
				</view>
				<view class="item" style="background-color: #FFEDED;">
					<view class="tit">600元以下</view>
					<view class="num" style="color: #D24D1F;">{{(kanbanDatas.customerCountBelow500/10).toFixed(1)}}%</view>
					<view class="tag">月消</view>
				</view>
				<view class="item" style="background-color: #FFEDED;">
					<view class="tit">未订货客户</view>
					<view class="num" >{{kanbanDatas.noOrderCustomerCountInner30}}</view>
					<view class="tag">10天</view>
				</view>
				<view class="item">
					<view class="tit">订单数量</view>
					<view class="num" style="color: #D24D1F;">{{kanbanDatas.orderNumYesterday}}</view>
					<view class="tag">昨日</view>
				</view>
				<view class="item">
					<view class="tit">订单金额</view>
					<view class="num" style="color: #D24D1F;">{{kanbanDatas.salesMoneyYesterday}}</view>
					<view class="tag">昨日</view>
				</view>
				<view class="item">
					<view class="tit">实收数量</view>
					<view class="num" style="color: #D24D1F;">{{kanbanDatas.factNumYesterday}}</view>
					<view class="tag">昨日</view>
				</view>
				<view class="item">
					<view class="tit">实收金额</view>
					<view class="num" style="color: #D24D1F;">{{kanbanDatas.factMoneyYesterday}}</view>
					<view class="tag">昨日</view>
				</view>
			</view>
		</view>
		<!-- 同比环比分析 -->
		<view class="c-bd" v-show="activeIndex == 2">
			<view>
				<canvas canvas-id="canvasColumnStack" id="canvasColumnStack" class="charts" disable-scroll=true  @touchstart="touchColumn1" @touchmove="moveColumn1" @touchend="touchEndColumn1"></canvas>
			</view>
			<view class="sales-num flex">
				<view class="item flex">
					<view class="l">{{tongbiDatas.lastYear}}年</view>
					<view class="r">销售总额：{{lastMoneyTotal}}</view>
				</view>
				<view class="item flex">
					<view class="l">{{tongbiDatas.year}}年</view>
					<view class="r">销售总额：{{currentMoneyTotal}}</view>
				</view>
			</view>
		</view>
		<!-- 区间时间选择 -->
		<w-picker
			mode="range" 
			startDate="1997" 
			endYear="2030"
			 :defaultVal="rangeDval"
			:current="false"
			@confirm="onConfirm" 
			@cancel = "onCancel"
			ref="range" 
			themeColor="#f00"
		></w-picker>
	</view>
</template>

<script>
	import WucTab from '@/components/wuc-tab/wuc-tab.vue'
	import wPicker from "@/components/w-picker/w-picker.vue";
	import uCharts from '@/components/u-charts/u-charts.js'
	import Request from '@/request/request.js'
	import dayjs from '@/common/dayjs.min.js'
	let _self;
	let canvaColumn=null;//销售分析图表
	let canvaColumn1 = null //环比分析图表
	let canvaColumn1Data = null
	export default{
		components: {
			WucTab,
			wPicker
		},
		data() {
			return {
				// rangeDval:['2019-02-01','2020-02-07'],
				rangeDval:[dayjs().subtract(1, 'year').format('YYYY-MM-DD'),dayjs().format('YYYY-MM-DD')],
				beginDate:'',//销售分析开始时间
				endDate:'',//销售分析结束时间
				navItems:[
					{id:0,name:'销售分析'},
					{id:1,name:'数据看板'},
					{id:2,name:'环比分析'}
				],
				activeIndex:0,
				cWidth: '',
				cHeight: '',
				pixelRatio: 1,
				tongbiDatas:{},
				salesDatas:[],
				kanbanDatas:{},//数据看板集合
				radarImg:'',//解决小程序canvas层级过高问题
			}
		},
		created() {
			_self = this;
			this.cWidth=uni.upx2px(750);
			this.cHeight=uni.upx2px(600);
			this.getSales()//获取销售数据
			
			this.getKanBan()//获取看板数据
		},
		methods:{
			tabChange(index) {
			    this.activeIndex = index;
					if(index == 2&&!canvaColumn1){
						this.getTongbiData()//获取同比分析数据
					}
			},
			toggleTab(str){
				// #ifdef MP-WEIXIN
				this.handleCanvarToImg(this.$refs[str].show)
				// #endif
				// #ifndef MP-WEIXIN
				this.$refs[str].show();
				// #endif
				// this.$refs[str].show();
			},
			onConfirm(val){
				// #ifdef MP-WEIXIN
				this.radarImg = ''
				// #endif
				this.beginDate = val.from
				this.endDate = val.to
				this.getSales()
				
			},
			onCancel(){
				// #ifdef MP-WEIXIN
				this.radarImg = ''
				// #endif
			},
			handleCanvarToImg(callback){
				uni.canvasToTempFilePath({
					x: 0,
					y: 0,
					width: _self.cWidth,
					height: _self.cHeight,
					canvasId: 'canvasColumn',
					success:function(res) {
						_self.radarImg = res.tempFilePath
						callback&&callback()
					},
					fail:function(err){
						console.log(err)
					}
				},this)
			},
			getKanBan(){
				Request({
					url: 'rq/dataKanban',
					method:'GET'
				}).then(res => {
					if(res.code == 0){
						this.kanbanDatas = res.data
					}
				})
			},
			getSales(){
				Request({
					url: 'rq/salesRq',
					data:{
						beginDate:this.beginDate,
						endDate:this.endDate
					}
				}).then(res => {
					// _self.fillData(res.data);
					this.salesDatas = res.data.salesMoneylist
					let Column={categories:[],series:[]};
					//这里我后台返回的是数组，所以用等于，如果您后台返回的是单条数据，需要push进去
					Column.categories=res.data.gnames;
					Column.series= [
						{name:'销售金额',data:res.data.salesMoneylist},
						{name:'销售数量',data:res.data.salesNumlist}
					];
					
					 _self.showColumn("canvasColumn",Column)
				
				})
			},
			getTongbiData(){
				Request({url:'rq/tongbihuanbiRq',method:'GET'})
					.then(res =>{
						let ColumnStack={categories:[],series:[]};
						//这里我后台返回的是数组，所以用等于，如果您后台返回的是单条数据，需要push进去
						ColumnStack.categories=['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'];
						this.tongbiDatas = res.data
						this.tongbiDatas.currentYearData = this.tongbiDatas.currentYearData.map(item => {return Number(item)})
						this.tongbiDatas.lastYearData = this.tongbiDatas.lastYearData.map(item => {return Number(item)})
						/* ColumnStack.series=[{name:res.data.lastYear,data:[35, 36, 31, 33, 13, 34,35, 36, 31, 33, 13, 34]},{name:res.data.year,data:[18, 27, 21, 24, 6, 28,18, 27, 21, 24, 6, 28]}] */
						ColumnStack.series=[{name:res.data.lastYear,data:this.tongbiDatas.lastYearData},{name:res.data.year,data:this.tongbiDatas.currentYearData}]
						// _self.showColumnStack("canvasColumnStack",ColumnStack);
						// _self.$nextTick(()=>{
						// 	 _self.showColumnStack("canvasColumnStack",ColumnStack)
						// })
						
						_self.showColumnStack("canvasColumnStack",ColumnStack)
						
					}).catch(err =>{
						console.log(err)
						})
			},
			showColumn(canvasId,chartData){
				canvaColumn=new uCharts({
					$this:_self,
					canvasId: canvasId,
					type: 'column',
					fontSize:11,
					padding:[5,15,15,15],
					legend:{
						show:true,
						position:'top',
						float:'center',
						itemGap:30,
						padding:5,
						margin:20,
						// backgroundColor:'rgba(41,198,90,0.2)',
						//borderColor :'rgba(41,198,90,0.5)',
						borderWidth :1
					},
					dataLabel:true,
					dataPointShape:true,
					background:'#FFFFFF',
					pixelRatio:_self.pixelRatio,
					categories: chartData.categories,
					series: chartData.series,
					animation: false,
					enableScroll: true,
					xAxis: {
						disableGrid:false,
						type:'grid',
						gridType:'dash',
						itemCount:6,
						scrollShow:false,
						scrollAlign:'left',
						rotateLabel:true
					},
					yAxis: {
						//disabled:true
						gridType:'dash',
						splitNumber:4,
						min:10,
						max:180,
						format:(val)=>{return val.toFixed(0)}//如不写此方法，Y轴刻度默认保留两位小数
					},
					width: _self.cWidth*_self.pixelRatio,
					height: _self.cHeight*_self.pixelRatio,
					extra: {
						column: {
							type:'group',
							width: _self.cWidth*_self.pixelRatio*0.45/chartData.categories.length
						}
					},
				});
				
			},
			showColumnStack(canvasId,chartData){
				canvaColumn1=new uCharts({
					$this:_self,
					canvasId: canvasId,
					type: 'column',
					padding:[15,15,0,15],
					legend:{
						show:true,
						position:'bottom',
						float:'center',
						itemGap:30,
						padding:5,
						margin:20,
						// backgroundColor:'rgba(41,198,90,0.2)',
						//borderColor :'rgba(41,198,90,0.5)',
						borderWidth :1
					},
					fontSize:11,
					background:'#FFFFFF',
					pixelRatio:_self.pixelRatio,
					animation: false,
					categories: chartData.categories,
					series: chartData.series,
					enableScroll: true,
					xAxis: {
						disableGrid:false,
						type:'grid',
						gridType:'dash',
						itemCount:6,
						scrollShow:false,
					},
					yAxis: {
						gridType:'dash',
						format:(val)=>{return val.toFixed(0) + '元'}
					},
					dataLabel: true,
					width: _self.cWidth*_self.pixelRatio,
					height: _self.cHeight*_self.pixelRatio,
					extra: {
						column: {
							type:'stack',
							width: _self.cWidth*_self.pixelRatio*0.8/chartData.categories.length
						}
					  }
				});
				
			},
			touchColumn(e){
				canvaColumn.scrollStart(e);
			},
			moveColumn(e) {
				canvaColumn.scroll(e);
			},
			touchEndColumn(e) {
				canvaColumn.scrollEnd(e);
				canvaColumn.touchLegend(e, {
					animation:false,
				});
				canvaColumn.showToolTip(e, {
					format: function (item, category) {
						return category + ' ' + item.name + ':' + item.data 
					}
				});
			},
			touchColumn1(e){
				canvaColumn1.scrollStart(e);
				
			},
			moveColumn1(e) {
				canvaColumn1.scroll(e);
			},
			touchEndColumn1(e) {
				canvaColumn1.scrollEnd(e);
				canvaColumn1.touchLegend(e);
				canvaColumn1.showToolTip(e, {
					format: function (item, category) {
						return category + ' ' + item.name + ':' + item.data + '元'
					}
				});
			},
		},
		computed:{
			lastMoneyTotal(){
				let total = 0;
				this.tongbiDatas.lastYearData&&this.tongbiDatas.lastYearData.forEach(item =>{
					total += Number(item)
				})
				return total.toFixed(2) + '元'
			},
			currentMoneyTotal(){
				let total = 0;
				this.tongbiDatas.currentYearData&&this.tongbiDatas.currentYearData.forEach(item =>{
					total += Number(item)
				})
				return total.toFixed(2) + '元'
			},
			salesTotal(){
				let total = 0;
				this.salesDatas.forEach(item =>{
					total += Number(item)
				})
				return total.toFixed(2) + '元'
			}
		}
	}
</script>

<style lang="less" scoped>
	.ana-ad{
		height: 100%;
		width: 100%;
		background-color: #FFFFFF;
		.header{
			height: 100rpx;
			
		}
		.c-bd{
			height: calc(100% - 100rpx);
			.selects{
				// height: 240rpx;
				// background-color: #ccc;
				padding:60rpx 30rpx 0;
				align-items: center;
				.tit{
					width: 100rpx;
					text-align: right;
				}
				.content{
					margin-left: 28rpx;
					flex: 1;
					justify-content: space-between;
					line-height: 60rpx;
					.st-time,.ed-time{
						text-align: center;
						height: 60rpx;
						width: 240rpx;
						border: 1px solid #C0C0C0;
						&.placeholder{
							color: #C0C0C0;
						}
					}
				}
			}
			/* canvsa宽高 */
			.charts {
				width: 750upx;
				height: 600upx;
				background-color: #FFFFFF;
			}
			/* 小程序端canvas层级过高 */
			.radarImg{
				width: 750upx;
				height: 600upx;
			}
			.total{
				font-size: 36rpx;
				text-align: center;
				margin: 30rpx;
			}
			.sales-num{
				flex-direction: column;
				align-items: center;
				.item{
					width: 70%;
					// border:1px solid #ccc;
					margin-bottom: 30rpx;
					// justify-content: space-between;
					.l{
						position: relative;
						padding-left: 40rpx;
						width: 160rpx;
						&::before{
							content: '';
							background-color: #1890ff;
							width: 34rpx;
							height: 18rpx;
							position:absolute;
							top:10rpx;
							left: 0;
						}
					}
					&:last-child{
						.l{
							&::before{
								background-color: #2fc25b;
							}
						}
					}
				}
			}
			.kanban{
				margin: 32rpx 80rpx 0;
				flex-wrap: wrap;
				justify-content: space-between;
				.item{
					width: 45%;
					height: 200rpx;
					border: 1px solid rgb(120, 176, 255);
					background-color: #DCF0F9;
					margin-bottom: 52rpx;
					// border-radius: 14rpx;
					padding: 60rpx 54rpx 0;
					font-size: 28rpx;
					text-align: center;
					position: relative;
					.num{
						margin-top: 16rpx;
						font-size: 40rpx;
						color: #535050;
						
					}
					&:nth-child(n+3){
						.num{
							color: #EC4B18;
						}
					}
					.tag{
						width: 76rpx;
						height: 40rpx;
						background-color: #3C79F9;
						position: absolute;
						top: 0;
						left: 0;
						text-align: center;
						line-height: 40rpx;
						color: #fff;
						font-size: 24rpx;
						border-radius: 0 20rpx 0 20rpx;
					}
				}
			}
		}
	}
</style>
